<template>
  <div class="device-stats-container">
    <el-card shadow="never" class="stats-card">
      <template #header>
        <div class="card-header">
          <span>设备统计</span>            <el-button type="primary" size="small" @click="refreshStats">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="stats-item">
              <div class="stats-icon total-icon">
                <el-icon><Monitor /></el-icon>
              </div>
              <div class="stats-content">
                <div class="stats-value">{{ statsData.total }}</div>
                <div class="stats-label">总设备数</div>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="stats-item">
              <div class="stats-icon active-icon">
                <el-icon><VideoPlay /></el-icon>
              </div>
              <div class="stats-content">
                <div class="stats-value">{{ statsData.active }}</div>
                <div class="stats-label">已启用设备</div>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="stats-item">
              <div class="stats-icon disabled-icon">
                <el-icon><VideoPause /></el-icon>
              </div>
              <div class="stats-content">
                <div class="stats-value">{{ statsData.disabled }}</div>
                <div class="stats-label">已禁用设备</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <el-card shadow="never" class="chart-card">
        <template #header>
          <div class="card-header">
            <span>设备分布</span>
            <el-select v-model="chartType" size="small" @change="updateChart">
              <el-option label="设备类型分布" value="type"></el-option>
              <el-option label="设备状态分布" value="status"></el-option>
            </el-select>
          </div>
        </template>
        <div class="chart-container" ref="chartContainer"></div>
      </el-card>

      <el-card shadow="never" class="recent-devices-card">
        <template #header>
          <div class="card-header">
            <span>最近添加的设备</span>
            <el-button text type="primary" @click="viewAllDevices">
              查看全部
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
        </template>
        <el-table :data="recentDevices" style="width: 100%" v-loading="loading">
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="设备名称" width="150"></el-table-column>
          <el-table-column prop="deviceCode" label="设备编号" width="150"></el-table-column>
          <el-table-column prop="type" label="设备类型" width="150">
            <template #default="scope">
              {{ getDeviceTypeText(scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdTime" label="创建时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.createdTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="viewDeviceDetail(scope.row.id)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, onUnmounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { Refresh, Monitor, VideoPlay, VideoPause, ArrowRight } from '@element-plus/icons-vue';
  import * as echarts from 'echarts';
  
  const router = useRouter();
  const loading = ref(false);
  const chartType = ref('type');
  const chartContainer = ref(null);
  let chart = null;
  
  // 统计数据
  const statsData = reactive({
    total: 0,
    active: 0,
    disabled: 0
  });
  
  // 最近添加的设备
  const recentDevices = ref([]);
  
  // 获取设备统计数据
  const fetchDeviceStats = async () => {
    try {
      const response = await fetch('/api/device/stats', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      
      const data = await response.json();
      
      if (data.code === 200) {
        statsData.total = data.data.total;
        statsData.active = data.data.active;
        statsData.disabled = data.data.disabled;
        
        // 更新图表
        updateChart();
      } else {
        ElMessage.error(data.message || '获取设备统计数据失败');
      }
    } catch (error) {
      console.error('获取设备统计数据失败:', error);
      ElMessage.error('获取设备统计数据失败');
    }
  };
  
  // 获取最近添加的设备
  const fetchRecentDevices = async () => {
    loading.value = true;
    try {
      const response = await fetch('/api/device/list?pageNum=1&pageSize=5', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      
      const data = await response.json();
      
      if (data.code === 200) {
        recentDevices.value = data.data.records;
      } else {
        ElMessage.error(data.message || '获取最近设备失败');
      }
    } catch (error) {
      console.error('获取最近设备失败:', error);
      ElMessage.error('获取最近设备失败');
    } finally {
      loading.value = false;
    }
  };
  
  // 刷新统计数据
  const refreshStats = () => {
    Promise.all([fetchDeviceStats(), fetchRecentDevices()]).then(() => {
      ElMessage.success('统计数据已刷新');
    });
  };
  
  // 查看所有设备
  const viewAllDevices = () => {
    router.push('/device/list');
  };
  
  // 查看设备详情
  const viewDeviceDetail = (id) => {
    router.push(`/device/${id}`);
  };
  
  // 更新图表
  const updateChart = () => {
    if (!chartContainer.value) return;
    
    if (!chart) {
      chart = echarts.init(chartContainer.value);
    }
    
    let option;
    
    if (chartType.value === 'type') {
      // 模拟设备类型分布数据（这里应该从API获取）
      option = {
        title: {
          text: '设备类型分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['LCD屏幕', 'LED显示屏', '数字标牌', '触摸屏', '信息亭', '其他']
        },
        series: [
          {
            name: '设备类型',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: 10, name: 'LCD屏幕' },
              { value: 15, name: 'LED显示屏' },
              { value: 20, name: '数字标牌' },
              { value: 8, name: '触摸屏' },
              { value: 6, name: '信息亭' },
              { value: 3, name: '其他' }
            ]
          }
        ]
      };
    } else {
      // 设备状态分布
      option = {
        title: {
          text: '设备状态分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['已启用', '已禁用']
        },
        series: [
          {
            name: '设备状态',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: statsData.active, name: '已启用' },
              { value: statsData.disabled, name: '已禁用' }
            ]
          }
        ]
      };
    }
    
    chart.setOption(option);
  };
  
  // 格式化日期时间
  const formatDateTime = (dateTime) => {
    if (!dateTime) return '未知';
    const date = new Date(dateTime);
    return date.toLocaleString();
  };
  
  // 获取设备类型文本
  const getDeviceTypeText = (type) => {
    const typeMap = {
      'LCD_SCREEN': 'LCD屏幕',
      'LED_DISPLAY': 'LED显示屏',
      'DIGITAL_SIGNAGE': '数字标牌',
      'TOUCH_SCREEN': '触摸屏',
      'INTERACTIVE_KIOSK': '信息亭',
      'OTHER': '其他'
    };
    return typeMap[type] || '未知';
  };
  
  // 处理窗口大小变化
  const handleResize = () => {
    if (chart) {
      chart.resize();
    }
  };
  
  onMounted(() => {
    fetchDeviceStats();
    fetchRecentDevices();
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);
  });
  
  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', handleResize);
    
    // 销毁图表实例
    if (chart) {
      chart.dispose();
      chart = null;
    }
  });
  </script>
  
  <style scoped>
  .device-stats-container {
    padding: 20px;
  }
  
  .stats-card,
  .chart-card,
  .recent-devices-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .stats-item {
    display: flex;
    align-items: center;
    padding: 20px 0;
  }
  
  .stats-icon {
    width: 60px;
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 50%;
    margin-right: 15px;
  }
  
  .stats-icon .el-icon {
    font-size: 30px;
    color: white;
  }
  
  .total-icon {
    background-color: #409eff;
  }
  
  .active-icon {
    background-color: #67c23a;
  }
  
  .disabled-icon {
    background-color: #f56c6c;
  }
  
  .stats-content {
    display: flex;
    flex-direction: column;
  }
  
  .stats-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 5px;
  }
  
  .stats-label {
    color: #909399;
    font-size: 14px;
  }
  
  .chart-container {
    height: 400px;
    width: 100%;
  }
  
  @media (max-width: 768px) {
    .stats-item {
      margin-bottom: 20px;
    }
  }
  </style>